﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

namespace SalaryChannel.Web
{
    [ServiceContract(Namespace = "http://salary.yangchao.ts.gs.chinamobile/")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PrizeService : ServiceAuthRoot
    {
        [OperationContract]
        public List<string> GetPrize(bool IsGetNonValid, string CountyCode)
        {
            // 在此处添加操作实现
            try
            {
                this.Authoricate();
                using (PrizeDataClassesDataContext context = new PrizeDataClassesDataContext())
                {
                    var query = from q in context.Prize
                                where DateTime.Now >= q.Valid_Time && DateTime.Now <= q.Expire_Time
                                where IsGetNonValid || q.Is_Valid == '1'
                                where q.Valid_County == null || q.Valid_County == "0" || q.Valid_County.Contains(CountyCode)
                                select q;

                    List<string> ret = new List<string>();
                    if (query.Any())
                    {
                        foreach (var a in query)
                        {
                            ret.Add(string.Format("[{0}]{1}", a.ID, a.Prize_Name));
                        }
                    }
                    return ret;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PrizeService.GetPrize:" + ex.Message);
                return null;
            }
        }

        // 在此处添加更多操作并使用 [OperationContract] 标记它们

        [OperationContract]
        public List<Prize_Items> GetPrizeItemsByID(short PrizeID)
        {
            try
            {
                this.Authoricate();
                using (PrizeDataClassesDataContext context = new PrizeDataClassesDataContext())
                {
                    context.ObjectTrackingEnabled = false;
                    var query = from q in context.Prize_Items
                                where q.Prize_ID == PrizeID
                                where q.Is_Valid == '1'
                                where DateTime.Now >= q.Valid_Time
                                where DateTime.Now <= q.Expire_Time
                                orderby q.Probability
                                select q;

                    List<Prize_Items> ret = new List<Prize_Items>();
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return ret;
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PrizeService.GetPrizeItemsByID:" + ex.Message);
                return null;
            }
        }
        [OperationContract]
        public int UploadPrizeResult(
            string PhoneID,
            short PrizeID,
            string CreateID)
        {
            try
            {
                lock (this)
                {
                    this.Authoricate();
                    using (PrizeDataClassesDataContext context = new PrizeDataClassesDataContext())
                    {

                        SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                        cmd.Connection = (System.Data.SqlClient.SqlConnection)context.Connection;
                        cmd.CommandText = "SP_GetValidPrizeItems";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add(new SqlParameter("@prizeID", PrizeID));

                        System.Data.DataTable table = new System.Data.DataTable();
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(table);

                        if (table.Rows.Count == 0)
                        {
                            return -1;// "当前奖品已全部兑完";
                        }

                        Random r = new Random((int)DateTime.Now.Ticks);

                        int probablity = r.Next(1, 10000);
                        Prize_His newHis = new Prize_His
                        {
                            Create_ID = CreateID,
                            Create_Time = DateTime.Now,
                            Phone_ID = PhoneID
                        };
                        //Dictionary<string, short> tem = new Dictionary<string, short>(11);

                        //if (tem.ContainsKey(PhoneID))
                        //{
                        //    newHis.Prize_Items = context.Prize_Items.First(b => b.ID == tem[PhoneID]);
                        //}
                        //else
                        {
                            foreach (DataRow i in table.Rows)
                            {
                                if (probablity <= int.Parse(i["pro"].ToString()))
                                {
                                    newHis.Prize_Items = context.Prize_Items.Where(y => y.ID == short.Parse(i["id"].ToString())).First();
                                    break;
                                }
                            }
                        }

                        if (newHis.Prize_Items == null)
                        {
                            return -2;// "奖项概率设置异常，请联系管理员";
                        }

                        context.Prize_His.InsertOnSubmit(newHis);
                        context.SubmitChanges();

                        return newHis.Prize_Items.ID;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PrizeService.UploadPrizeResult:" + ex.Message);
                return -999;
            }
        }


        [OperationContract]
        public Prize_His IsUserPrizeDone(
            string PhoneID,
            short PrizeID)
        {
            try
            {
                this.Authoricate();
                using (PrizeDataClassesDataContext context = new PrizeDataClassesDataContext())
                {
                    context.ObjectTrackingEnabled = false;
                    if(context.Prize.First(x=>x.ID==PrizeID).Can_Repeat=='1')
                    {
                        return new Prize_His { ID = -1 };
                    }
                    var query = from q in context.Prize_His
                                join b in context.Prize_Items on q.Prize_Item_ID equals b.ID
                                where b.Prize_ID == PrizeID
                                where q.Phone_ID == PhoneID                              
                                select q;
                    if (query.Any())
                    {
                        return query.First();
                    }
                    return new Prize_His { ID = -1 };
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("PrizeService.IsUserPrizeDone:" + ex.Message);
                return null;
            }
        }
    }
}
